package com.zliblike_platform.service.impl;

import com.zliblike_platform.entity.User;
import com.zliblike_platform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Spring Security UserDetailsService实现
 * 用于将自定义用户实体转换为Spring Security需要的UserDetails对象
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {
        // 查找用户，可以通过用户名或邮箱
        User user = userService.findByUsernameOrEmail(usernameOrEmail);
        
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + usernameOrEmail);
        }
        
        // 创建权限列表
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        
        // 基本权限
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        
        // 检查用户角色字段
        if (user.getRole() != null) {
            if (user.getRole().contains("ADMIN")) {
                authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
            if (user.getRole().contains("VIP")) {
                authorities.add(new SimpleGrantedAuthority("ROLE_VIP"));
            }
        }
        
        // 返回Spring Security UserDetails对象
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(),  // 用户名
            user.getPassword(),  // 加密后的密码
            user.getEnabled() != null ? user.getEnabled() : true,  // 账户是否启用
            true,               // 账户是否未过期
            true,               // 凭证是否未过期
            true,               // 账户是否未锁定
            authorities         // 权限列表
        );
    }
} 